package com.chis.netty.http.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chis.jm.bean.JmMailException;
import com.chis.sms.main.Testmain;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 
 * @Description 
 * @Company zwx
 * @author wlj
 * @version 2019年12月19日
 */
public class HttpServerHandler extends ChannelInboundHandlerAdapter {

    private String result = "";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FullHttpRequest)) {
            result = "未知请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        try {
            String path = httpRequest.uri();          //获取路径 uri路径,可以根据 这个判断请求接口
            String body = getBody(httpRequest);     //获取参数
            HttpMethod method = httpRequest.method();//获取请求方法
//            System.out.println("接收到:" + method + " 请求:"+path);
//            if (!path.startsWith("/test")) {
//                result = "无效请求";
//                send(ctx, result, HttpResponseStatus.BAD_REQUEST);
//                return;
//            }
            //如果是GET请求
            if (HttpMethod.GET.equals(method)) {
                //接受到的消息，做业务逻辑处理...
                send(ctx, result, HttpResponseStatus.BAD_REQUEST);
                return;
            }
            //如果是POST请求
            if (HttpMethod.POST.equals(method)) {
                //接受到的消息，做业务逻辑处理...
                try {
                    System.out.println("=============="+body);
                    Thread.sleep(5000);
                    

//                    JSONObject jsonObject = JSON.parseObject(body);
//                    String d = jsonObject.getString("commonAnnotations");
//                    String ddd = (String) JSON.parseObject(d).get("summary");
//                    短信预警
//                    Testmain.sendmymsg("13915513476",ddd);
//                    微信预警
//                    new JmMailException("育苗通监控:" + body,new Exception());

                    result = handresp();
                } catch (Exception e){
                    e.printStackTrace();
                    result = handrespFail(e.getMessage());
                }
                send(ctx, result, HttpResponseStatus.OK);
            }
        } catch (Exception e) {
            System.out.println("处理请求失败!");
            e.printStackTrace();
        } finally {
            //释放请求
            httpRequest.release();
        }
    }

    public static void main(String[] args) {
        String s = "{\"receiver\":\"web\\\\.hook\",\"status\":\"firing\",\"alerts\":[{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.107:9101\",\"job\":\"node_export\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.107:9101 已停止运行超过 15s！\"},\"startsAt\":\"2020-07-24T09:30:04.321474606Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://yfjz-107:9090/graph?g0.expr=up%7Bjob%3D%22node_export%22%7D+%3D%3D+0\\u0026g0.tab=1\",\"fingerprint\":\"b5a62fb083f6c124\"}],\"groupLabels\":{\"alertname\":\"node-up\"},\"commonLabels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.107:9101\",\"job\":\"node_export\",\"severity\":\"1\",\"team\":\"node\"},\"commonAnnotations\":{\"summary\":\"10.88.88.107:9101 已停止运行超过 15s！\"},\"externalURL\":\"http://yfjz-107:9095\",\"version\":\"4\",\"groupKey\":\"{}:{alertname=\\\"node-up\\\"}\",\"truncatedAlerts\":0}\n";
        JSONObject jsonObject = JSON.parseObject(s);
        String d = jsonObject.getString("commonAnnotations");
        System.out.println();

    }


    private String handresp(){
        //{"resp":{"status":0,"message":"请求成功","body":{"buz_status":0,"buz_message":"业务处理成功"},"event_id":"0ac98c13c2e14aff9d6413192b1bbb3d"}}
        Map<String,Object> map = new HashMap<>();
        map.put("status",0);
        map.put("message","请求成功");
        Map<String,Object> map1 = new LinkedHashMap<>();
        map1.put("buz_status",0);
        map1.put("buz_message","处理成功");
        map.put("body",map1);
        Map<String,Object> map2 = new LinkedHashMap<>();
        map2.put("resp",map);
        return JSON.toJSONString(map2);
    }

    private String handrespFail(String msg){
        //{"resp":{"status":0,"message":"请求成功","body":{"buz_status":0,"buz_message":"业务处理成功"},"event_id":"0ac98c13c2e14aff9d6413192b1bbb3d"}}
        Map<String,Object> map = new HashMap<>();
        map.put("status",0);
        map.put("message","请求成功");
        Map<String,Object> map1 = new LinkedHashMap<>();
        map1.put("buz_status",-1);
        map1.put("buz_message","处理失败:"+msg);
        map.put("body",map1);
        Map<String,Object> map2 = new LinkedHashMap<>();
        map2.put("resp",map);
        return JSON.toJSONString(map2);
    }

    /**
     * 获取body参数
     */
    private String getBody(FullHttpRequest request) {
        ByteBuf buf = request.content();
        return buf.toString(CharsetUtil.UTF_8);
    }

    /**
     * 发送的返回值
     */
    private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    /*
     * 建立连接时，返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());
        ctx.writeAndFlush("客户端" + InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接！ ");
        super.channelActive(ctx);
    }
    

}
